package com.online.shopping.service.impl;

import com.alibaba.fastjson.JSON;
import com.online.shopping.custom.Goods;
import com.online.shopping.mapper.*;
import com.online.shopping.pojo.*;
import com.online.shopping.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Transactional
public class GoodsServiceImpl implements GoodsService {

	@Autowired
	private TbBrandMapper brandMapper;
	@Autowired
	private TbGoodsMapper goodsMapper;
	@Autowired
	private TbGoodsDescMapper goodsDescMapper;
	@Autowired
	private TbItemMapper itemMapper;
	@Autowired
	private TbItemCatMapper itemCatMapper;
	@Autowired
	private TbSellerMapper sellerMapper;

	@Override
	public List<TbGoods> search(TbGoods searchEntity) {
		TbGoodsExample example = new TbGoodsExample();
		TbGoodsExample.Criteria criteria = example.createCriteria();

		if(!"".equals(searchEntity.getGoodsName()) && searchEntity.getGoodsName()!=null){
			criteria.andGoodsNameLike("%"+searchEntity.getGoodsName()+"%");
		}
		if(!"".equals(searchEntity.getAuditStatus()) && searchEntity.getAuditStatus()!=null){
			criteria.andAuditStatusEqualTo(searchEntity.getAuditStatus());
		}
		criteria.andIsDeleteIsNull();
		return goodsMapper.selectByExample(example);
	}

	@Override
	public Goods findOne(Long id) {
		Goods goods = new Goods();

		// 查询商品表的信息
		goods.setGoods(goodsMapper.selectByPrimaryKey(id));

		// 查询商品扩展表的信息
		goods.setGoodsDesc(goodsDescMapper.selectByPrimaryKey(id));

		// 查询SKU表的信息
		TbItemExample example = new TbItemExample();
		TbItemExample.Criteria criteria = example.createCriteria();

		criteria.andGoodsIdEqualTo(id);
		goods.setItemList(itemMapper.selectByExample(example));

		return goods;
	}

	@Override
	public void add(Goods goods) {
		goods.getGoods().setAuditStatus("0");   // 设置审核的状态
		goodsMapper.insert(goods.getGoods());   // 插入商品信息   tb_goods   spu（回填主键id到pojo对象中）

		System.out.println("回填的主键："+goods.getGoods().getId());
		goods.getGoodsDesc().setGoodsId(goods.getGoods().getId());  // 设置tb_goods_desc表的外键和主键

		goodsDescMapper.insert(goods.getGoodsDesc());   // 插入商品的扩展信息
		setItemList(goods);     // 保存sku信息
	}

	@Override
	public void update(Goods goods) {
		// 修改商品信息
		goods.getGoods().setAuditStatus("0");
		goodsMapper.updateByPrimaryKey(goods.getGoods());

		// 修改商品扩展信息
		goodsDescMapper.updateByPrimaryKey(goods.getGoodsDesc());

		// 修改SKU信息
		// 先删除
		TbItemExample example = new TbItemExample();
		TbItemExample.Criteria criteria = example.createCriteria();

		criteria.andGoodsIdEqualTo(goods.getGoods().getId());
		itemMapper.deleteByExample(example);

		// 后保存
		setItemList(goods);
	}

	@Override
	public void updateStatus(Long[] goodsIds, String status) {
		for (Long id : goodsIds){
			TbGoods tbGoods = goodsMapper.selectByPrimaryKey(id);

			tbGoods.setAuditStatus(status);

			goodsMapper.updateByPrimaryKey(tbGoods);
		}
	}

	@Override
	public List<TbItem> findItemListByGoodsIdListAndStatus(Long[] goodsIds, String status) {
		TbItemExample example = new TbItemExample();
		TbItemExample.Criteria criteria = example.createCriteria();

		criteria.andStatusEqualTo(status);
		criteria.andGoodsIdIn(Arrays.asList(goodsIds));     // 指定条件：SPUID集合
		return itemMapper.selectByExample(example);

	}

	@Override
	public void delete(Long[] ids) {
		for(Long id : ids){
			TbGoods tbGoods = goodsMapper.selectByPrimaryKey(id);
			tbGoods.setIsDelete("1");
			goodsMapper.updateByPrimaryKey(tbGoods);
		}
	}

	private void setItemList(Goods goods) {
		System.out.println("是否启用规格：" + goods.getGoods().getIsEnableSpec());

		if("1".equals(goods.getGoods().getIsEnableSpec())){
			// 启用规格
			// 保存SKU列表的信息
			for(TbItem item : goods.getItemList()){
				// 设置SKU的数据
				// item.setTitle(title);
				String title = goods.getGoods().getGoodsName();
				Map<String,String> map = JSON.parseObject(item.getSpec(), Map.class);
				for (String key : map.keySet()) {
					title += " "+map.get(key);
				}
				item.setTitle(title);
				setValue(goods,item);

				itemMapper.insert(item);
			}
		}else{
			// 没有启用规格
			TbItem item = new TbItem();

			item.setTitle(goods.getGoods().getGoodsName());

			item.setPrice(goods.getGoods().getPrice());
			item.setNum(999);
			item.setStatus("0");
			item.setIsDefault("1");
			item.setSpec("{}");

			setValue(goods,item);
			itemMapper.insert(item);
		}
	}

	private void setValue(Goods goods, TbItem item) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String date = sdf.format(new Date());

		item.setCategoryid(goods.getGoods().getCategory3Id());
		try {
			item.setCreateTime(sdf.parse(date));
			item.setUpdateTime(sdf.parse(date));
		} catch (ParseException e) {
			e.printStackTrace();
		}

		// 获取图片路径
		System.out.println("图片数据："+goods.getGoodsDesc().getItemImages());
		String imageString = goods.getGoodsDesc().getItemImages();
		String imageMap = imageString.substring(1, imageString.length()-1);
		System.out.println("数据处理后："+imageMap);

		if(!"".equals(imageMap) && imageMap!=null){
			// 添加图片路径
			Map<String, String> map = JSON.parseObject(imageMap, Map.class);
			item.setImage(map.get("url"));
		}

		// 添加商品id和卖方id
		item.setGoodsId(goods.getGoods().getId());
		item.setSellerId(goods.getGoods().getSellerId());

		// 模板
		item.setCategory(itemCatMapper.selectByPrimaryKey(goods.getGoods().getCategory3Id()).getName());
		// 添加brand
		item.setBrand(brandMapper.selectByPrimaryKey(goods.getGoods().getBrandId()).getName());
		// 添加seller
		item.setSeller(sellerMapper.selectByPrimaryKey(goods.getGoods().getSellerId()).getName());
	}
}
